const product = require('../../templates/product/list');

Page({
  data: {
    totalNum: 0,
    actions: [
      {
        name: '收藏',
        width: 64,
        color: '#FFF',
        fontsize: 28,
        background: '#FFC600',
        operate: 'collect'
      },
      {
        name: '看相似',
        color: '#FFF',
        fontsize: 28,
        width: 64,
        background: '#FF7035',
        operate: 'findSimilar'
      },
      {
        name: '删除',
        color: '#FFF',
        fontsize: 28,
        width: 64,
        background: '#F82400',
        operate: 'del'
      }
    ],
    actions2: [{
        name: '看相似',
        color: '#FFF',
        fontsize: 28,
        width: 64,
        background: '#FF7035'
      },
      {
        name: '删除',
        color: '#FFF',
        fontsize: 28,
        width: 64,
        background: '#F82400'
      }
    ],
    isEdit: false,
    cartList: [],
    invalidList: [],
    productList: [],
    pageIndex: 1,
    totalPrice: 0,
    loading: false,
    noMore: false,
    curSkuPrice: 0, // 显示当前商品在选择sku时对应的价格
    curSkuData: []  // 用于匹配用户选择sku后，查找相应的sku价格
  },
  onLoad: async function () {
    this.getProduct();
  },
  onShow: async function () {
    if (!this.data.isLogined) {
      this.setData({
        isLogined: await wx.user.hasLogin()
      }, () => {
        this.getCart();
      });
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      pageIndex: 1,
      cartList: [],
      invalidList: [],
      productList: [],
      hasCart: false,
      hasInvalid: false,
      noMore: false,
      loading: false
    }, () => {
      this.getCart();
      this.getProduct();
      wx.stopPullDownRefresh();
    });
  },
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },
  onReachBottom: function () {
    if (this.data.noMore) return;
    this.setData({
      loading: true
    }, () => {
      this.getCart();
      this.getProduct();
    });
  },
  onHide: function () {
    this.hidePopup();
    this.hideModal();
  },
  getCart: function () {
    if (this.data.isLogined) {
      wx.util.request(this, {
        body: {
          page: this.data.pageIndex
        }
      }).then(res => {
        let valid = [], invalid = [];
        for (let item of res) {
          let skuPrice = (item.sku ? item.sku.price : 0);
          item.depreciate = Number(item.price > skuPrice ? item.price - skuPrice : 0).toFixed(2);
          if (item.ladderPreferential.length > 0) {
            let lp = item.ladderPreferential[0],
                price = lp.price;
            item.quantity = lp.quantity;
            if (lp.type == 1) {
              item.describe = `减${price}元`;
            } else {
              item.describe = (Math.round(price) / 10) + '折';
            }
          }
          if (item.status == 1) {
            item.product.max_buy = (item.product.max_buy == 0 ? item.sku.stock : item.product.max_buy);
            valid.push(item);
          } else {
            invalid.push(item);
          }
        }
        this.setData({
          pageIndex: this.data.pageIndex + 1,
          cartList: this.data.cartList.concat(valid),
          invalidList: this.data.invalidList.concat(invalid),
          hasCart: valid.length > 0,
          hasInvalid: invalid.length > 0,
          noMore: res.length < 10
        });
      }).catch(err => {
        console.log(err);
      });
    }
  },
  getProduct: function () {
    if (this.data.noMore) return;
    wx.util.request('product.guess').then(res => {
      let list = this.data.productList;
      for (let item of res) {
        list.push(item);
      }
      this.setData({
        productList: list
      });
    });
  },
  detail: function (e) {
    wx.navigateTo({
      url: `../product/detail?id=${e.currentTarget.dataset.id}`
    })
  },
  productSku: function (e) {
    let idx = e.currentTarget.dataset.index,
        item = this.data.cartList[idx],
        curSkuPrice = this.data.curSkuPrice;
    wx.util.request('product.sku', {
      query: `product_id=${item.product_id}`
    }).then(res => {
      let skuData = item.sku.data,
          skuArr = skuData.split('-');
      // 默认选中
      for (let baf of res.base_attribute_format) {
        for (let val of baf.value) {
          if (skuArr.indexOf(val.base_spec_value_id) > -1) val.checked = true;
        }
      }
      // 当前sku价格
      for (let sku of res.sku) {
        if (sku.data == skuData) curSkuPrice = sku.price;
      }
      this.setData({
        popupShow: true,
        cartIdx: idx,
        oldSkuId: item.sku_id,
        sku: res.sku,
        baf: res.base_attribute_format,
        curSkuPrice: curSkuPrice
      });
    });
  },
  selectSku: function (e) {
    let d = this.data,
        baf = d.baf,
        curSkuPrice = d.curSkuPrice,
        curSkuData = d.curSkuData;
    // 更新项目的展示状态
    for (let item of baf[e.currentTarget.dataset.index].value) {
      item.checked = false;
      if (item.base_spec_value_id == e.detail.value) {
        item.checked = true;
        curSkuData[e.currentTarget.dataset.index] = item.base_spec_value_id;
      }
    }
    // 获取新sku的价格
    let skuData = curSkuData.join('-');
    for (let sku of d.sku) {
      if (sku.data == skuData) curSkuPrice = sku.price;
    }
    this.setData({
      baf: baf,
      curSkuData: curSkuData,
      curSkuPrice: curSkuPrice || d.curSkuPrice
    });
  },
  changeSku: function () {
    let skuId, skuData = '', d = this.data, baf = d.baf;
    for (let attr of baf) {
      for (let item of attr.value) {
        if (item.checked) skuData += (skuData ? '-' : '') + item.base_spec_value_id;
      }
    }
    for (let s of d.sku) {
      if (s.data == skuData) {
        skuId = s.id;
        break;
      }
    }
    if (d.oldSkuId != skuId) {
      wx.util.request('cart.modifySku', {
        body: {
          sku_id: d.oldSkuId,
          new_sku_id: skuId
        }
      }).then(product => {
        this.setData({
          [`cartList[${d.cartIdx}].depreciate`]: 0,
          [`cartList[${d.cartIdx}].ladderPreferential`]: product.ladderPreferential,
          [`cartList[${d.cartIdx}].sku`]: product.sku
        });
      });
    }
    this.hidePopup();
  },
  hidePopup: function () {
    this.setData({
      popupShow: false
    });
  },
  toPage: function (e) {
    wx.switchTab({
      url: `../${e.currentTarget.dataset.page}/index`,
    });
  },
  checkboxChange: function (e) {
    let totalNum = 0,
        list = this.data.cartList,
        idxs = e.detail.value,
        totalPrice = 0;
    for (let i in list) {
      list[i].checked = false;
      if (idxs.indexOf(i) > -1) {
        totalNum++;
        list[i].checked = true;
        totalPrice += list[i].sku.price * list[i].number;
      }
    }
    this.setData({
      totalNum: totalNum,
      totalPrice: totalPrice
    });
  },
  selectAll: function (e) {
    //wx.util.toast('功能正在完善');
    let list = this.data.cartList, totalNum = 0, totalPrice = 0;
    for (let item of list) {
      if (item.sku.stock <= 0) continue;
      totalNum++;
      item.checked = !item.checked;
      if (item.checked) totalPrice += item.sku.price * item.number;
    }
    this.setData({
      cartList: list,
      totalNum: totalNum,
      totalPrice: totalPrice
    });
  },
  changeNum: function (e) {
    let index = e.detail.index,
        num = e.detail.value,
        list = this.data.cartList[index],
        minBuy = list.product.min_buy;
    if (num <= minBuy) {
      num = minBuy;
    }
    wx.util.request('cart.modifyNum', {
      body: {
        sku_id: list.sku.id,
        num: num
      }
    }).then(res => {
      this.setData({
        [`cartList[${index}].number`]: num
      });
    });
  },
  sliderBtn: function (e) {
    let index = e.detail.index,
        id = e.detail.item.product.id,
        skuId = e.detail.item.sku.id,
        operate = this.data.actions[index].operate;
    if (operate == 'collect') {
      // 添加我的收藏
      wx.util.request('common.collect.new', {
        body: {
          topic_id: id,
          topic_type: 'product'
        }
      }).then(res => {
        wx.util.toast('已收藏');
      });
    } else if (operate == 'findSimilar') {
      // 找相似
      wx.util.toast('功能开发中');
    } else if (operate == 'del') {
      // 移除商品
      this.remove(skuId);
    }
  },
  edit: function () {
    this.setData({
      isEdit: !this.data.isEdit
    });
  },
  settlement: function () { 
    wx.showLoading(); 
    let ids = []; 
    for (let item of this.data.cartList) { 
      if (item.checked) ids.push(item.id); 
    } 
    wx.hideLoading(); 
    wx.navigateTo({
      url: '../order/submit?type=cart&data=' + ids.join() 
    }); 
  },
  remove: function (skuId) { 
    let arr = [], ids = [], list = this.data.cartList; 
    if (skuId && (typeof skuId == 'string')) { 
      ids.push(skuId); 
    } else { 
      for (let item of list) { 
        if (item.checked) ids.push(item.sku.id); 
      } 
    } 
    wx.util.request('cart.remove', { 
      body: {
        sku_ids: JSON.stringify(ids)
      }
    }).then(res => {
      wx.util.toast('已移出购物车');
      this.updateList('cart', list, ids);
    });
  },
  showModal: function () {
    this.setData({
      modal: true
    });
  },
  hideModal: function () {
    this.setData({
      modal: false
    });
  },
  /**
   * 清空失效商品
   */
  empty: function (e) {
    if (e.detail.index === 1) {
      wx.util.request('cart.empty', {
        body: {lose_status: 1}
      }).then(res => {
        wx.util.toast('已清空');
        let ids = [], list = this.data.invalidList;
        for (let item of list) {
          ids.push(item.sku.id);
        }
        this.updateList('invalid', list, ids);
      });
    }
    this.hideModal();
  },
  detail: function (e) {
    product.detail(e);
  },
  updateList: function (flagName, list, arr) {
    let newArr = [];
    let convert = flagName.charAt(0).toUpperCase() + flagName.slice(1);
    for (let item of list) {
      if (arr.indexOf(item.sku.id) < 0) newArr.push(item);
    }
    this.setData({
      [`${flagName}List`]: newArr,
      [`has${convert}`]: (newArr.length > 0)
    });
  },
  similar: function (e) {
    product.similar(e.currentTarget.dataset.kw);
  }
})